﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using Core.Library;

namespace CMS.Handlers
{
    /// <summary>
    /// Summary description for StorageHandler
    /// </summary>
    public class StorageHandler : IHttpHandler
    {
        protected string SecretKey = WebConfigurationManager.AppSettings["SecretKey"];
        protected string LargeFile = WebConfigurationManager.AppSettings["LargeFile"];
        protected string SmallFile = WebConfigurationManager.AppSettings["SmallFile"];

        public StorageHandler()
        {
            FillMimes();
        }

        public void ProcessRequest(HttpContext context)
        {
            string command = "";
            if (context.Request.RequestType == "POST")
            {
                if (context.Request["command"] != null)
                {
                    command = context.Request["command"];
                }
                else
                {
                    return;
                }
            }
            else
            {
                if (context.Request.QueryString["command"] != null)
                {
                    command = context.Request.QueryString["command"];
                }
                else
                {
                    return;
                }
            }

            switch (command.ToLower())
            {
                case "viewdirectories":
                    ViewDirectories(context);
                    break;
                case "makedir":
                    MakeDir(context);
                    break;
                case "removedir":
                    RemoveDir(context);
                    break;
                case "deletefile":
                    DeleteFile(context);
                    break;
                case "renamefile":
                    RenameFile(context);
                    break;
            }
        }

        protected Dictionary<string, string> Mimes;

        private void FillMimes()
        {
            if (Mimes == null) Mimes = new Dictionary<string, string>();
            Mimes.Add(".jpeg", "image/jpeg");
            Mimes.Add(".jpg", "image/jpeg");
            Mimes.Add(".gif", "image/gif");
            Mimes.Add(".png", "image/png");
        }

        private string GetMime(string fileName)
        {
            if (fileName.Contains("."))
            {
                var ext = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));
                return Mimes.ContainsKey(ext) ? Mimes[ext] : string.Empty;
            }
            return string.Empty;
        }

        public void ViewDirectories(HttpContext context)
        {
            var dirName = context.Request["dirname"];

            var urlAction = string.Format("{0}ls?secret_key={1}&dirname={2}", SmallFile, SecretKey, dirName);
            var response = HttpMethodHelper.HttpGet(urlAction, null);
            var reader = new StreamReader(response.GetResponseStream());
            var result = reader.ReadToEnd();
            reader.Close();
            response.Close();
            context.Response.Write(result);
        }

        public void MakeDir(HttpContext context)
        {
            var dirName = HttpUtility.HtmlDecode(context.Request["dirname"]);

            var urlAction = string.Format("{0}make_dir?secret_key={1}&dirname={2}", SmallFile, SecretKey, dirName);
            var response = HttpMethodHelper.HttpGet(urlAction, null);
            var result = false;
            if (response.StatusCode == HttpStatusCode.OK) result = true;
            response.Close();

            var objSerial = new JavaScriptSerializer();
            var json = objSerial.Serialize(result);
            context.Response.Write(json);
        }

        public void RemoveDir(HttpContext context)
        {
            var dirName = context.Request["dirname"];

            var urlAction = string.Format("{0}remove_dir?secret_key={1}&dirname={2}", SmallFile, SecretKey, dirName);
            var response = HttpMethodHelper.HttpGet(urlAction, null);
            var result = false;
            if (response.StatusCode == HttpStatusCode.OK) result = true;
            response.Close();

            var objSerial = new JavaScriptSerializer();
            var json = objSerial.Serialize(result);
            context.Response.Write(json);
        }

        public void DeleteFile(HttpContext context)
        {
            var filename = context.Request["filename"];
            if (!string.IsNullOrEmpty(filename))
            {
                var urlAction = string.Format("{0}delete?secret_key={1}&filename={2}", SmallFile, SecretKey, filename);
                var response = HttpMethodHelper.HttpGet(urlAction, null);
                var result = false;
                if (response.StatusCode == HttpStatusCode.OK) result = true;
                response.Close();

                var objSerial = new JavaScriptSerializer();
                var json = objSerial.Serialize(result);
                context.Response.Write(json);
            }
        }

        public void RenameFile(HttpContext context)
        {
            var from = context.Request["from"];
            var to = context.Request["to"];

            var urlAction = string.Format("{0}rename?secret_key={1}&from={2}&to={3}", SmallFile, SecretKey, from, to);
            var response = HttpMethodHelper.HttpGet(urlAction, null);
            var result = false;
            if (response.StatusCode == HttpStatusCode.OK) result = true;
            response.Close();

            var objSerial = new JavaScriptSerializer();
            var json = objSerial.Serialize(result);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}